<?php

namespace app\service;

use app\model\DistributionSetting;
use app\model\Goods;
use app\model\GoodsInfo;
use app\model\Shop;
use think\facade\Log;
use Wechat\CommerceApp;

class GoodsService
{
    public static function getGoodsList(int $type, int $share_ratio, string $next_key = '')
    {
        $sum = 0;
        try {
            [$product_list, $next_key] = CommerceApp::getInstance()->goodsLists($type, $next_key);
            $next_key = $next_key ?? '';

            $goods_ids = $shop_ids = $save = $shop_save = $info_save = [];
            foreach ($product_list as $item) {
                $sum++;
                $goods_ids[] = $item['product_id'];
                $shop_ids[]  = $item['shop_appid'];
            }
            $goods_data  = Goods::field('id, product_id, status, shop_appid, head_supplier_appid')->where('product_id', 'in', $goods_ids)->select()->toArray();
            $product_ids = $head_supplier_appids = $index_goods = [];
            if ($goods_data) {
                $index_goods = array_column($goods_data, null, 'product_id');
            }
            foreach ($goods_data as $item) {
                $product_ids[]          = $item['product_id'];
                $head_supplier_appids[] = $item['head_supplier_appid'];
            }
            $shop_data = Shop::field('id, shop_appid')->where('shop_appid', 'in', $shop_ids)->select()->toArray();
            $shop_ids  = array_column($shop_data, 'shop_appid');

            foreach ($product_list as $item) {
                $productId         = $item['product_id'];
                $shopAppId         = $item['shop_appid'];
                $headSupplierAppid = $item['head_supplier_appid'] ?? '';
                //只有商品不存在数据库才进行保存，存在则暂时不处理
                $shouldSave = !in_array($productId, $product_ids);

                //$shouldSave || (!in_array($headSupplierAppid, $head_supplier_appids)) || (!in_array($shopAppId, $shop_ids))
                if ($shouldSave) {
                    try {
                        [$goods, $goods_info] = self::createGoodsSaveData($shopAppId, $productId, $type, $headSupplierAppid, $share_ratio);
                        $save[]      = $goods;
                        $info_save[] = $goods_info;

                        if (!in_array($shopAppId, $shop_ids)) {
                            try {
                                $shop        = self::createShopSaveData($shopAppId, $productId);
                                $shop_save[] = $shop;
                            } catch (\Exception $e) {
                                $log = [
                                    'msg'   => '获取商品基础详情失败',
                                    'error' => $e->getMessage(),
                                    'data'  => $item,
                                ];
                                Log::error($log);
                            }
                        }
                    } catch (\Exception $e) {
                        $log = [
                            'msg'   => '获取商品详情失败',
                            'error' => $e->getMessage(),
                            'data'  => $item,
                        ];
                        Log::error($log);
                    }
                } else {
                    try {
                        $info            = CommerceApp::getInstance()->goodsDetail($shopAppId, $productId, $type, $headSupplierAppid);
                        $commission_info = $info['commission_info'];
                        if ($commission_info['status'] != $index_goods[$productId]['status']) {
                            $save[] = [
                                'id'     => $index_goods[$productId]['id'],
                                'status' => $commission_info['status'],
                            ];
                        }
                    } catch (\Exception $e) {
                        $save[] = [
                            'id'     => $index_goods[$productId]['id'],
                            'status' => 2,
                        ];
                    }

                }
            }
            return [$save, $shop_save, $info_save, $next_key, $sum];
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            exit;
        }
    }


    /**
     * 封装数据库商品保存数据
     * @param string $shop_appid
     * @param string $product_id
     * @param int $plan_type
     * @param string $head_supplier_appid
     * @return array[]
     */
    public static function createGoodsSaveData(string $shop_appid, string $product_id, int $plan_type, string $head_supplier_appid = '', int $share_ratio = 0)
    {
        try {
            $info            = CommerceApp::getInstance()->goodsDetail($shop_appid, $product_id, $plan_type, $head_supplier_appid);
            $product_info    = $info['product_info'];
            $head_imgs       = $product_info['head_imgs'] ?? [];
            $sku             = $product_info['skus'][0];
            $commission_info = $info['commission_info'];
            $commission_rate = $commission_info['service_ratio'] / 10000;
            $commission      = round($sku['sale_price'] * $commission_rate / 100);
            if ($share_ratio > 0) {
                $share_commission = round($commission * ($share_ratio / 100));
            } else {
                $share_commission = round($commission / 2);
            }
            if ($plan_type == 3 || $plan_type == 1) {
                $type = 1;
            } else {
                $type = 2;
            }
            $goods      = [
                'product_id'             => $product_id,
                'shop_appid'             => $shop_appid,
                'head_supplier_appid'    => $head_supplier_appid,
                'title'                  => $product_info['title'],
                'product_promotion_link' => $product_info['product_promotion_link'],
                'image'                  => $head_imgs[0] ?? '',
                'sale_price'             => $sku['sale_price'],
                'stock_num'              => $sku['stock_num'],
                'source'                 => $type,
                'merchant_type'          => $type,
                'is_square'              => $plan_type == 4 ? 1 : 0,
                'commission_rate'        => $commission_rate,
                'commission'             => $commission,
                'share_commission'       => $share_commission,
                'subsidy_commission'     => 0,
                'status'                 => $commission_info['status'],
                'head_imgs'              => json_encode($head_imgs),
                'plan_type'              => $plan_type,
            ];
            $goods_info = [
                'product_id'         => $product_id,
                'product_info'       => json_encode($product_info, JSON_UNESCAPED_UNICODE),
                'commission_info'    => json_encode($commission_info, JSON_UNESCAPED_UNICODE),
                'head_supplier_info' => !empty($info['head_supplier_info']) ? json_encode($info['head_supplier_info'], JSON_UNESCAPED_UNICODE) : [],
            ];
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
        return [$goods, $goods_info];
    }

    /**
     * 封装数据库店铺保存数据
     * @param string $shop_appid
     * @param string $product_id
     * @return array
     * @throws \Exception
     */
    public static function createShopSaveData(string $shop_appid, string $product_id)
    {
        try {
            $base_info = CommerceApp::getInstance()->goodsBaseDetail($shop_appid, $product_id);
            $shop      = [
                'shop_appid' => $shop_appid,
                'name'       => $base_info['shop']['name'],
                'image'      => $base_info['shop']['icon'],
                'score'      => $base_info['shop']['score'],
            ];
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
        return $shop;
    }
}
